'use strict'
const audioSource = document.querySelector("select#audioSource");
const audioOutput = document.querySelector("select#audioOutput");
const videoSource = document.querySelector("select#videoSource");

const doPlayer = document.getElementById('doPlayer');
const filterSelect = document.getElementById('filter');
const snapshot = document.getElementById('snapshot');

const video = document.getElementById('videoplayer');
const audio = document.getElementById('audioplayer');
const canvas = document.getElementById('canvas');
canvas.width = 640;
canvas.height = 480;
const info = document.getElementById('info');


/**
 * 视频特效-视频滤镜
 */
filterSelect.addEventListener('change',function(){
	video.className = filterSelect.value
})

/**
 * 截图
 */
snapshot.addEventListener('click',function(){
	// 设置滤镜
	canvas.className = filterSelect.value;
	// 截图
	canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
})

/**
 * 获取媒体数据
 */
 doPlayer.addEventListener('click',function(){
	getUserMedia()
 })

function getUserMedia() {
	// const constrants = {
	// 	video: true,
	// 	audio: true
	// }
	// 约束设置
	const constrants = {
		video: {
			width: 640,
			height: 480,
			// 帧率，每秒有多少张图片，影响视频卡顿
			frameRate: 60,
			// user:前置;environment:后置摄像头;
			facingMode: 'user'
			// 设备ID
			// deviceId: ''
		},
		audio: {
			// 音量
			// volume: 50,
			// 降噪
			noiseSuppression: true,
			// 回音消除
			echoCancellation:true,
			// 
			autoGainControl:true
			// 
		}
	}
	navigator.mediaDevices.getUserMedia(constrants)
		.then(onGetMedia)
		.catch(onMedia_error)
}

function onGetMedia(stream) {
	video.srcObject = stream
	// audio.srcObject = stream
	window.stream= stream;

	const videoTrack = stream.getVideoTracks()[0]
	var videoConstrains = videoTrack.getSettings();
	info.textContent = JSON.stringify(videoConstrains)
	// 获取媒体留数据后调用该方法就可以让浏览器弹出提示框，是否允许使用媒体设备
	getDeviceList()
}

function onMedia_error(err) {
	console.log('获取媒体失败');
}


getDeviceList()
/**
 * 读取设备列表
 */
function getDeviceList() {
	if (!navigator.mediaDevices ||
		!navigator.mediaDevices.enumerateDevices) {
		console.log('enumerateDevices is not supported!');
	} else {
		navigator.mediaDevices.enumerateDevices()
			.then(gotDevices)
			.catch(handleError);
	}
}

function gotDevices(deviceInfos) {
	deviceInfos.forEach(function (deviceInfo) {
		console.log(deviceInfo.kind + ": label = " +
			deviceInfo.label + ": id = " +
			deviceInfo.deviceId + ": groupId = " +
			deviceInfo.groupId);
		var option = document.createElement('option');
		option.text = deviceInfo.label;
		option.value = deviceInfo.deviceId;
		if (deviceInfo.kind === 'audioinput') {
			audioSource.appendChild(option);
		} else if (deviceInfo.kind === 'audiooutput') {
			audioOutput.appendChild(option);
		} else if (deviceInfo.kind === 'videoinput') {
			videoSource.appendChild(option);
		}
	});

}

function handleError(err) {
	console.log(err.name + " : " + err.message);
}
////////////////////////////////////////////////////////////////
const record = document.getElementById('record');
const replay = document.getElementById('replay');
const download = document.getElementById('download');
const recvideo = document.getElementById('recvideo');
let stream;
let mediaRecorder;
let buffer;

/**
 * 录制
 */
 record.addEventListener('click',function(){
	if(record.value === '录制'){
		startRecord();	
		record.value = 'Stop Record';
		replay.disabled = true;
		download.disabled = true;
	}else{
		stopRecord();
		record.value = '录制';
		replay.disabled = false;
		download.disabled = false;
	}
	
})
/**
 * 播放
 */
replay.addEventListener('click',function(){
	let blob = new Blob(buffer,{type: 'video/webm'})
	recvideo.src = window.URL.createObjectURL(blob)
	recvideo.srcObject = null;
	recvideo.controls = true;
	recvideo.play();
})

/**
 * 下载
 */
download.addEventListener('click',function(){
	let blob = new Blob(buffer,{type: 'video/webm'})
	let url = window.URL.createObjectURL(blob)
	let a = document.createElement('a');
	a.href = url;
	a.style.display = 'none';
	a.download = 'downavigator.webm'
	a.click()
})

/**
 * 录制视频
 * @param {*} stream 
 */
function startRecord(stream){
	buffer = [];
	const option = {
		mimeType: 'video/webm;codecs=vp8'
	}
	mediaRecorder = new MediaRecorder(window.stream,option)
	mediaRecorder.start(10)
	mediaRecorder.ondataavailable = handleRecorder
}
function handleRecorder(e){
	if(e&& e.data && e.data.size >0){
		buffer.push(e.data)
	}
}
/**
 * 停止录制
 */
function stopRecord(){
	mediaRecorder.stop()
}

///////////////////////////////////////////////
// 输入 chrome://flags/
// 打开插件为可用  Experimental Web Platform features

const desktop = document.getElementById('desktop');
desktop.addEventListener('click',function(){
	const option = {
		video: true
	}
	navigator.mediaDevices.getDisplayMedia(option)
	.then(onGetMedia)
	.catch(onMedia_error)
})